import os
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
import logging
logging.basicConfig(level=logging.INFO)
from sm_system.models import *
from supplier.views import index as supplier_index
from contract.views import index as contract_index
from tools import encrypt_md5, id_generate
# Create your views here.



BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
COOKIE_NAME = 'sm_session'


def index(request):

    id = str(request.COOKIES.get(COOKIE_NAME))[4:]
    context = {'user': None, 'admin': ''}
    if not id:
        context['user'] = ''
    else:
        try:
            context['user'] = AdminInfo.objects.get(id=id).name
        except Exception as e:
            logging.info(e)

        context['admin'] = 'admin'
    return render(request, 'seniorAdmin/index_sm.html', context)


def login(request):

    return render(request, 'seniorAdmin/login_sm.html')


def authenticate(request):

    id = request.POST.get('id')
    password = request.POST.get('password')

    content = {'message': '', 'user': None, 'admin': ''}
    try:
        admin_info = AdminInfo.objects.get(id=id)
    except Exception as e:
        logging.info(e)
        content['message'] = '该用户不存在！'
        return JsonResponse(content)

    if encrypt_md5(password) == admin_info.password:
        content['user'] = admin_info.name
        res = JsonResponse(content)
        res.set_cookie(COOKIE_NAME, (admin_info.supermarket_id+admin_info.id), max_age=86400, httponly=True)
        return res
    else:
        content['message'] = '输入的信息有误！'
        return JsonResponse(content)


def logout(request):

    rep = redirect("/seniorAdmin/login/")
    rep.delete_cookie(COOKIE_NAME)  # 删除用户浏览器上之前设置的cookie值
    return rep

